<template>
    <div class="app-container">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox formBox1" :model="queryParams" ref="queryForm" size="small" :inline="true"
                v-show="showSearch" label-width="68px">
                <el-form-item label="选择医院">
                    <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="180px"
                        :isUserAll="true" ref="departments">
                    </department>
                </el-form-item>
                <el-form-item label="治疗项目">
                    <el-select v-model="queryParams.planId" filterable placeholder="请选择治疗项目" clearable style="width: 160px">
                        <el-option v-for="item in planList" :key="item.planId" :label="item.medicalEquipment"
                            :value="item.planId"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="周次">
                    <el-input v-model="weekNum" placeholder="周次" style="width:80px;margin:0 10px;"
                        @input="weekNum = weekNum.replace(/^(0+)|[^\d]+/g, '')" @keyup.enter.native="InputWeek"
                        class="inputNum" />

                </el-form-item> -->
                <!-- <el-button type="primary" icon="el-icon-search" size="mini" @click="InputWeek"
                    style="margin-right:10px;">搜索</el-button> -->
                <el-form-item label="预约时间">
                    <el-date-picker v-model="dateRange" style="width: 200px;margin-right:10px;"
                        :picker-options="pickerOptions" value-format="yyyy-MM-dd" type="daterange" size="mini"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery"
                        :clearable="false"></el-date-picker><span style="color:#999;font-size:12px;">(默认显示本周)</span>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
                    <!-- <el-button icon="el-icon-printer" size="mini" type="success" @click="handleExport">导出</el-button> -->
                </el-form-item>
            </el-form>
            <div class="formBox">
                <!-- summary-method="getSummary" :summary-method="getSummaries"-->
                <el-table border v-loading="loading" :data="tableLists" show-summary  :summary-method="getSummaries" id="out-table" ref="table">
                    <!--                <el-table-column type="selection" width="50" align="center" />-->
                    <!-- <el-table-column label="序号" align="center" type="index" width="50" fixed>
                        <template slot-scope="scope">
                            <span>{{ getIndex(scope.$index) }}</span>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="治疗项目" align="center" prop="medicalEquipment" :show-overflow-tooltip="true"
                        width="160" fixed />
                    <el-table-column :label="getLabel(item)" align="center" v-for="(item, index) in dateList" :key="index">


                        <el-table-column align="center" prop="appointmentsNumber" label="开放数（人次）" width="80">

                                <template slot-scope="scope">
                                    <span v-if="scope.row.rtList[index].appointmentsNumber" style="font-size:16px">{{
                                        scope.row.rtList[index].appointmentsNumber }}</span>
                                    <span v-else>-</span>

                                </template>


                        </el-table-column>
                        <el-table-column prop="appointmentsMadeNum" align="center" label="已预约数（人次）" width="80">
                            <template slot-scope="scope">
                                <span v-if="scope.row.rtList[index].appointmentsMadeNum" style="color:blue;font-size:16px;text-decoration: underline;cursor: pointer;" @click="showdetail(scope.row,scope.row.rtList[index])">{{
                                    scope.row.rtList[index].appointmentsMadeNum }}</span>
                                <span v-else>-</span>

                            </template>
                        </el-table-column>
                        <el-table-column prop="balance" align="center" label="剩余数（人次）" width="80">
                            <template slot-scope="scope">
                                <span v-if="scope.row.rtList[index].balance" style="color:red;font-size:16px">{{
                                    scope.row.rtList[index].balance }}</span>
                                <span v-else>-</span>

                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table>
                <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
            </div>

        </el-row>
        <!-- 预约详情 -->
        <!-- 弹出预约提示 -->
        <el-dialog title="预约顾客信息" :visible.sync="appointPatientDialogVisible" v-dialogDrag width="85%" append-to-body
            :close-on-click-modal="false">
            <appointPatient v-if="appointPatientDialogVisible" :appointItem="appointItem"
                @closeappointPatientDialogVisible="closeappointPatientDialogVisible">
            </appointPatient>
        </el-dialog>
    </div>
</template>

<script>
//引入安装的依赖
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import XLSXD from "xlsx-style";
import department from "@/views/components/department/index.vue";
import appointPatient from "@/views/components/customerDetail/appointPatient.vue";
import { getTJappointment} from "@/api/appointManage/appointManage";
import {
    listPlan
} from "@/api/system/plan";
export default {
    name: "reservatieInfo",
    dicts: [

    ],
    components: { appointPatient, department },
    data() {
        let self = this
        return {
            pickerOptions: {
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '本月',
                    onClick(picker) {
                        const today = new Date();
                        const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                        const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                        picker.$emit('pick', [firstDayOfMonth, lastDayOfMonth]);
                    }
                }, {
                    text: '上周(第' + (self.splitDate("", 1) - 1) + '周)',
                    onClick(picker) {
                        self.dateSelect = -1
                        picker.$emit('pick', [self.getTime(7), self.getTime(1)]);
                    }
                }, {
                    text: '本周(第' + self.splitDate("", 1) + '周)',
                    onClick(picker) {
                        self.dateSelect = 0
                        picker.$emit('pick', [self.getTime(0), self.getTime(-6)]);
                    }
                }, {
                    text: '下周(第' + (self.splitDate("", 1) + 1) + '周)',
                    onClick(picker) {
                        self.dateSelect = 1
                        picker.$emit('pick', [self.getTime(-7), self.getTime(-13)]);
                    }
                }, {
                    text: '第' + (self.splitDate("", 1) + 2) + '周',
                    onClick(picker) {
                        picker.$emit('pick', [self.getTime(-14), self.getTime(-20)]);
                    }
                }, {
                    text: '第' + (self.splitDate("", 1) + 3) + '周',
                    onClick(picker) {
                        picker.$emit('pick', [self.getTime(-21), self.getTime(-27)]);
                    }
                }, {
                    text: '第' + (self.splitDate("", 1) + 4) + '周',
                    onClick(picker) {
                        picker.$emit('pick', [self.getTime(-28), self.getTime(-34)]);
                    }
                }, {
                    text: '第' + (self.splitDate("", 1) + 5) + '周',
                    onClick(picker) {
                        picker.$emit('pick', [self.getTime(-35), self.getTime(-41)]);
                    }
                }]
            },

            weekNum: undefined,
            appointPatientDialogVisible: false,
            appointItem: {},
            // 方案表格数据
            planList: null,
            dateList: null,
            intTableData: [],
            tableLists: [],
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 日期范围
            dateRange: [],
            // 表单参数
            // form: {},
            form: {

            },
            pageNum: 1,
            pageSize: 10,
            // 查询参数
            queryParams: {
                // pageNum: 1,
                // pageSize: 10,
                hospitalId: '',
                deptId: '',
                planId: '',

            },
        };
    },
    watch: {},
    computed: {

    },
    async created() {

    },
    mounted() {

    },
    methods: {

        handleWeek(num) {
            this.dateSelect = num
            if (num == -1) {
                //上周的开始时间
                // console.log(this.getTime(7));
                // //上周的结束时间
                // console.log(this.getTime(1));
                this.dateRange = [this.getTime(7), this.getTime(1)]
            } else if (num == 0) {
                //本周的开始时间
                // console.log(this.getTime(0));
                // //本周的结束时间
                // console.log(this.getTime(-6));
                this.dateRange = [this.getTime(0), this.getTime(-6)]
            } else if (num == 1) {
                //下周的开始时间
                // console.log(this.getTime(-7));
                //下周结束时间
                // console.log(this.getTime(-13));
                this.dateRange = [this.getTime(-7), this.getTime(-13)]
            } else if (num == -3) {//默认查本月的排班
                const today = new Date();
                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                var time0 = new Date(firstDayOfMonth);
                var time = new Date(lastDayOfMonth);
                var startTime = time0.getFullYear() + '-' + (time0.getMonth() + 1) + '-' + time0.getDate()
                var endTime = time.getFullYear() + '-' + (time.getMonth() + 1) + '-' + time.getDate()


                this.dateRange = [startTime, endTime]
            }
            // console.log(this.dateRange)
            if (this.dateRange == null || this.dateRange == undefined) {
                this.dateRange = []
            }
            this.getlistPlans()
        },
        closeappointPatientDialogVisible() {
            this.appointPatientDialogVisible = false
        },
        showdetail(obj,item){
            let appointItem={
                planId:obj.planId,
                medicalEquipment:obj.medicalEquipment,
                appointmentDate:item.appointmentDate,
                hospitalId:item.hospitalId,
                deptId:item.deptId,
                balance:item.balance,
                appointmentsNumber:item.appointmentsNumber,
                appointmentsMadeNum:item.appointmentsMadeNum,
                timeSlot:item.timeSlot,
            }
            this.appointItem=appointItem
            this.appointPatientDialogVisible = true
        },
        getSummaries(param) {
            let that = this
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                // if (index === 1) {
                //     return;
                // }
                let indexof = parseInt((index - 1) / 3)
                // console.log(indexof)

                const values = data.map(item => Number(item.rtList[indexof][column.property]));
                // console.log(values)
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] += '';
                } else {
                    sums[index] = '';
                }


            });
            return sums;
        },
        /** 导出按钮操作 */

        handleExport() {
            let tables = document.getElementById('out-table').cloneNode(true) // 重点
            tables.removeChild(tables.querySelector(".el-table__fixed")) // 重点
            let wb = XLSX.utils.table_to_book(tables, { sheet: '治疗业务统计' })
            this.setExlStyle(wb['Sheets']['治疗业务统计'])
            //合并单元格边框补齐
            this.addRangeBorder(wb['Sheets']['治疗业务统计']['!merges'], wb['Sheets']['治疗业务统计'])
            var ws = XLSXD.write(wb, {
                type: "buffer"
            });
            try {
                FileSaver.saveAs(
                    new Blob([ws], { type: "application/octet-stream" }),
                    `治疗业务统计_${this.dateRange[0]}~${this.dateRange[1]}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, ws);
            }
            return ws;

        },
        setExlStyle(data) {
            let borderAll = {//单元格外侧框线
                top: {
                    style: 'thin',
                },
                bottom: {
                    style: 'thin'
                },
                left: {
                    style: 'thin'
                },
                right: {
                    style: 'thin'
                }
            };
            data['!cols'] = [];
            for (let key in data) {
                if (data[key] instanceof Object) {
                    data[key].s = {
                        border: borderAll,
                        alignment: {
                            horizontal: 'center',//水平居中对齐
                            vertical: 'center'
                        },
                        font: {
                            sz: 11
                        },
                        bold: true,
                        numFmt: 0
                    }
                    data['!cols'].push({ wpx: 115 });
                }
            }
            return data;
        },
        addRangeBorder(range, ws) {
            let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
            range.forEach(item => {
                let startRowNumber = Number(item.s.c),
                    endRowNumber = Number(item.e.c);
                for (let i = startRowNumber; i <= endRowNumber; i++) {
                    for (let j = Number(item.s.r) + 1; j <= Number(item.e.r); j++) {
                        ws[`${arr[i]}${j + 1}`] = { s: { border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } } } };
                    }
                }

            })
            return ws;

        },
        getDatesBetween(start, end) {
            const dates = [];
            const currentDate = new Date(start);

            while (currentDate <= end) {
                dates.push(new Date(currentDate));
                currentDate.setDate(currentDate.getDate() + 1);
            }

            return dates;
        },
        formatDate(objDate, fmt) {
            var o = {
                "M+": objDate.getMonth() + 1, //月份
                "d+": objDate.getDate(), //日
                "h+": objDate.getHours() % 12 == 0 ? 12 : objDate.getHours() % 12, //小时
                "H+": objDate.getHours(), //小时
                "m+": objDate.getMinutes(), //分
                "s+": objDate.getSeconds(), //秒
                "q+": Math.floor((objDate.getMonth() + 3) / 3), //季度
                "S": objDate.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (objDate.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        /** 查询方案列表 */
        getlistPlans() {
            let that = this
            let params = {
                pageNum: 1,
                pageSize: 9999,
                status: 0,
                hospitalId: this.queryParams.hospitalId,
                planCategoryId: "2"
            }
            listPlan(params).then(
                (response) => {
                    let data = response.rows;
                    // console.log(data)
                    this.planList = data

                    this.handleQuery()
                });
        },
        getLabel(item){
          let text=item.timeSlot==0?(item.appointmentDate +' 上午'):(item.appointmentDate +' 下午')
           return text
        },
        refreshData(data) {
            console.log(data)
            if (data.hospitalId) {
                this.queryParams.hospitalId = data.hospitalId
                this.queryParams.deptId = data.deptId


            } else {
                this.queryParams.hospitalId = ''
                this.queryParams.deptId = ''
            }

            this.handleWeek(0)

        },
        InputWeek() {
            if (this.weekNum) {
                let currentWeek = this.splitDate('', 1)
                let yNum = Number(this.weekNum) - currentWeek
                this.dateRange = [this.getTime(-7 * yNum), this.getTime(-7 * yNum - 6)]
                this.handleQuery()
            } else {
                this.handleQuery()
            }

        },
        getTime(n) {
            var now = new Date();
            var year = now.getFullYear();
            //因为月份是从0开始的,所以获取这个月的月份数要加1才行
            var month = now.getMonth() + 1;
            var date = now.getDate();
            var day = now.getDay();
            // console.log(date);
            //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
            if (day !== 0) {
                n = n + (day - 1);
            } else {
                n = n + day;
            }
            if (day) {
                //这个判断是为了解决跨年的问题
                if (month > 1) {
                    month = month;
                }
                //这个判断是为了解决跨年的问题,月份是从0开始的
                else {
                    year = year - 1;
                    month = 12;
                }
            }
            now.setDate(now.getDate() - n);
            year = now.getFullYear();
            month = now.getMonth() + 1;
            date = now.getDate();
            // console.log(n);
            var s = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date);
            return s;
        },
        getYearWeek(a, b, c) {
            /*
            date1是当前日期
            date2是当年第一天
            d是当前日期是今年第多少天
            用d + 当前年的第一天的周差距的和在除以7就是本年第几周
            */
            var date1 = new Date(a, parseInt(b) - 1, c),
                date2 = new Date(a, 0, 1),
                d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
            return Math.ceil((d + ((date2.getDay() + 1) - 1)) / 7);
        },
        splitDate(date, type) {
            if (type == 1) {//本周
                var date0 = new Date();
                return this.getYearWeek(date0.getFullYear(), date0.getMonth() + 1, date0.getDate())
            } else {
                if (date) {
                    let dateArr = date.split('-')
                    return this.getYearWeek(dateArr[0], dateArr[1], dateArr[2])
                }
            }

        },

        getList() {
            let that = this
            // if (this.queryParams.hospitalId) {
                that.loading = true;
                let params = {
                    startTime: that.dateRange[0],
                    endTime: that.dateRange[1],
                    ...that.queryParams
                }
                getTJappointment(params).then((response) => {
                    if (response.code == 200) {
                        let data = response.data;
                        let arrB = data
                        let arrC = []
                        arrB.forEach(function (ele, index) {//最外层用户
                            let obj = {}
                            obj.medicalEquipment = ele.medicalEquipment
                            obj.planId = ele.planId
                            obj.rtList = []
                            let rtList = ele.rtList
                            that.dateList.forEach(function (planele, index1) {//大集合
                                let item = rtList.find(v => v.appointmentDate == planele.appointmentDate&&v.timeSlot == planele.timeSlot)
                                if (item) {
                                    obj.rtList.push(item)
                                } else {
                                    obj.rtList.push(planele)
                                }

                            })
                            arrC.push(obj)
                        })
                        this.tableLists = arrC

                    }
                    that.loading = false;
                });
            // } else {
            //     that.loading = false;
            // }
        },

        // 真实序号计算（计算分页影响）
        getIndex(index) {
            return (this.pageNum - 1) * this.pageNum + index + 1;
        },

        // 取消按钮
        cancel() {

        },
        // 表单重置
        reset() {

        },
        /** 搜索按钮操作 */
        handleQuery() {

            // this.queryParams.pageNum = 1;
          //生成日期集合  dateList
          let that = this
          this.dateList = []
          const startDate = new Date(that.dateRange[0]);
          const endDate = new Date(that.dateRange[1]);

          const datesInRange = this.getDatesBetween(startDate, endDate);

          datesInRange.forEach((date) => {
            let dateData=that.formatDate(date,"yyyy-MM-dd")

            for(var i=0;i<2;i++){
              let obj = {}
              obj.appointmentDate=dateData
              obj.appointmentsMadeNum =0
              obj.appointmentsNumber = 0
              obj.balance = 0
              obj.timeSlot=i
              this.dateList.push(obj)
            }

          })
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
        },
    },
};
</script>
<style scoped>

</style>
